package com.cmbc.xiaodu.dpl;

import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.certificate.Certificate;
import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.LaunchRequest;
import com.baidu.dueros.data.request.SessionEndedRequest;
import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.Reprompt;
import com.baidu.dueros.data.response.card.TextCard;
import com.baidu.dueros.data.response.directive.dpl.Document;
import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
import com.baidu.dueros.model.Request;
import com.baidu.dueros.model.Response;
import com.cmbc.xiaodu.BaseService;
import com.fasterxml.jackson.databind.JsonMappingException;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MinShengDplBot extends BaseBot {

    private String webappRoot = getClass().getResource("/").getPath().replaceAll("WEB-INF/classes/", "");
    private static Map<String, String> isLoginMap = new HashMap<String, String>();

    /**
     * 重写onInent方法，处理onInent对话事件
     * 此处为针对同一意图的多个槽位进行回复。
     */
    @Override
    protected Response onInent(IntentRequest intentRequest) {
        BaseService baseService;

        if (intentRequest.getIntentName().contains("手机银行")) {

            // 当用户表达 类似于 “打开我的手机银行” 时，触发登录
            return login();

        } else if ("queryAction".equals(intentRequest.getIntentName())) {

            // 多轮查询类
            /* 不需要登录的查询意图 */
            return this.billHandler();
        } else if ("pushAction".equals(intentRequest.getIntentName())) {

            //推送信息pushAction
            return this.newsHandler();
        } else if ("minPermissionAction".equals(intentRequest.getIntentName())) {

            /* 需要登录才能查询的意图 */
            // 在未登录客户端的情况下，先去登录；  如果已登录再去执行意图查询
            if (isLoginMap.containsKey("username") && isLoginMap.get("username") != null) {

                // 如果已登录，去执行具体的意图
                return this.balanceHandler();
            }
            return login();
        } else {
            return disUnderstand();
        }

    }

    /**
     * 处理用户登录需求
     * TODO 暂定这里涉及账户关联操作  （关联成功后 再次提示用户表述意图）
     */
    public Response login() {
        try {

            // 从json文件中初始化Document 解析json
//            Document document = Document.getDocumentFromPath("F:\\minshengWlw\\xiaodu_minsheng\\src\\main\\java\\com\\cmbc\\xiaodu\\dpl\\QR_code.json");
            Document document = Document.getDocumentFromPath(webappRoot+"json2.0/QR_code.json");

            // RenderDocument指令  （表达翻译json文档）
            RenderDocument renderDocument = new RenderDocument();
            renderDocument.setDocument(document);

            this.addDirective(renderDocument);

            // 返回语音内容
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请扫描二维码进行身份识别,然后再次表述您的意图");
            Response response = new Response(outputSpeech);
            isLoginMap.put("username", "tom");
            return response;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;

    }

    /**
     * TODO
     * 用来处理银行卡余额意图
     */
    public Response balanceHandler() {
        //baseService = new BalanceService();

        //  if (isLoginMap.containsKey("username") && isLoginMap.get("username") != null) {
        //如果登陆成功，即可查询余额
        if (null != getSlot("queryBalance") && getSlot("queryBalance").contains("余额")) {
            try {

                // 从json文件中初始化Document 解析json
//                Document document = Document.getDocumentFromPath("F:\\minshengWlw\\xiaodu_minsheng\\src\\main\\java\\com\\cmbc\\xiaodu\\dpl\\balance.json");
                Document document = Document.getDocumentFromPath(webappRoot+ "json2.0/balance.json");
                // RenderDocument指令  （表达翻译json文档）
                RenderDocument renderDocument = new RenderDocument();
                renderDocument.setDocument(document);

                this.addDirective(renderDocument);

                // 返回语音内容
                OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "username您好，您的账户余额为1000元");
                Response response = new Response(outputSpeech);
                return response;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }else {
            return disUnderstand();
        }
    }

    /**
     * TODO
     * 用来处理公共信用意图
     *
     * @return
     */
    private Response newsHandler() {
        return null;
    }

    /**
     * 咨询金融相关信息
     *
     * @return
     */
    private Response billHandler() {
        if (getSlot("exchangeRate") != null && getSlot("exchangeRate").contains("汇率")) {
            try {

//                String path = Thread.currentThread().getContextClassLoader().getResource("*/exchangeRate.json").getPath();
                // 从json文件中初始化Document 解析json
//                Document document = Document.getDocumentFromPath(path);
                Document document = Document.getDocumentFromPath(webappRoot+"json2.0/exchangeRate.json");

                // RenderDocument指令  （表达翻译json文档）
                RenderDocument renderDocument = new RenderDocument();
                renderDocument.setDocument(document);

                this.addDirective(renderDocument);

                // 返回语音内容
                OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "今日汇率是6.6");
                Response response = new Response(outputSpeech);
                return response;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        } else if (getSlot("SZIndex") != null && getSlot("SZIndex").equals("上证指数")) {
            try {

                // 从json文件中初始化Document 解析json
                Document document = Document.getDocumentFromPath(webappRoot+"json2.0/SZIndex.json");

                // RenderDocument指令  （表达翻译json文档）
                RenderDocument renderDocument = new RenderDocument();
                renderDocument.setDocument(document);

                this.addDirective(renderDocument);

                // 返回语音内容
                OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "今日上证指数123456");
                Response response = new Response(outputSpeech);
                return response;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        } else if (getSlot("goldPrice") != null && getSlot("goldPrice").equals("金价")) {
            try {

                // 从json文件中初始化Document 解析json
                Document document = Document.getDocumentFromPath(webappRoot+"json2.0/goldPrice.json");

                // RenderDocument指令  （表达翻译json文档）
                RenderDocument renderDocument = new RenderDocument();
                renderDocument.setDocument(document);

                this.addDirective(renderDocument);

                // 返回语音内容
                OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "今天金价为每克250元");
                Response response = new Response(outputSpeech);
                return response;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        } else {
           return disUnderstand();
        }
    }

    protected Response disUnderstand(){
        try {


            // 从json文件中初始化Document 解析json
//            Document document = Document.getDocumentFromPath("F:\\minshengWlw\\xiaodu_minsheng\\src\\main\\java\\com\\cmbc\\xiaodu\\dpl\\disUnderstand.json");
            Document document = Document.getDocumentFromPath(webappRoot+"json2.0/disUnderstand.json");

            // RenderDocument指令  （表达翻译json文档）
            RenderDocument renderDocument = new RenderDocument();
            renderDocument.setDocument(document);

            this.addDirective(renderDocument);

            // 返回语音内容
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "没听懂您的意思，您可以换个表达方式与我交流");
            Response response = new Response(outputSpeech);
            return response;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 重写onSessionEnded事件，处理onSessionEnded对话事件
     *
     * @param sessionEndedRequest SessionEndedRequest请求体
     * @see BaseBot#onSessionEnded(SessionEndedRequest)
     */
    @Override
    protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {

        try {
            isLoginMap.remove("username");
            // 从json文件中初始化Document 解析json
//            Document document = Document.getDocumentFromPath("/minsheng/src/main/java/com/cmbc/xiaodu/dpl/exit.json");
            Document document = Document.getDocumentFromPath(webappRoot+"json2.0/exit.json");

            // RenderDocument指令  （表达翻译json文档）
            RenderDocument renderDocument = new RenderDocument();
            renderDocument.setDocument(document);

            this.addDirective(renderDocument);

            // 构造OutputSpeech
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "username您好，您已经安全退出账户,欢迎再次使用民生服务");

            // 构造Response
            Response response = new Response(outputSpeech);

            return response;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 重写onLaunch方法，处理onLaunch对话事件
     *
     * @param launchRequest LaunchRequest请求体
     * @see BaseBot#onLaunch(LaunchRequest)
     */
    @Override
    protected Response onLaunch(LaunchRequest launchRequest) {
        /**
         * DPL
         */
        try {

//            String path = MinShengDplBot.class.getClassLoader().getResource("/json2.0/launch.json").getPath();
            // 从json文件中初始化Document 解析json
            Document document = Document.getDocumentFromPath(webappRoot+ "json2.0/launch.json");
//            Document document = Document.getDocumentFromPath(path);

            // RenderDocument指令  （表达翻译json文档）
            RenderDocument renderDocument = new RenderDocument();
            renderDocument.setDocument(document);

            this.addDirective(renderDocument);

            // 返回语音内容
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "欢迎使用民生服务");
            Response response = new Response(outputSpeech);
            return response;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /** ************************************************* 处理 账单意图 **************************     **/

    /**
     * 将得到的用户名和卡号 信息进行整合，返回最终的账单信息
     *
     * @return
     */
    private Response computeBill() {
        // 获取多轮槽位值：月薪值、城市信息、查询种类
        String userName = getSlot("userName");
        String cardNum = getSlot("cardNum");
        String ret = "用户名" + userName + "卡号" + cardNum + "总支出为：" + 999 + "总收入为：" + 1000;
        TextCard textCard = new TextCard(ret);
        textCard.setAnchorText("setAnchorText");
        textCard.addCueWord("查询成功");

        setSessionAttribute("key_1", "value_1");
        setSessionAttribute("key_2", "value_2");

        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, ret);
        Reprompt reprompt = new Reprompt(outputSpeech);
        // 主动结束会话
        this.endDialog();
        Response response = new Response(outputSpeech, textCard, reprompt);
        return response;
    }

    /**
     * 用来处理卡号的具体逻辑
     *
     * @return
     */
    private Response askCardNum() {
        TextCard textCard = new TextCard("您的卡号是多少?");
        textCard.setUrl("www:......");
        textCard.setAnchorText("setAnchorText");
        textCard.addCueWord("您的卡号是多少?");

        setSessionAttribute("key_1", "value_1");
        setSessionAttribute("key_2", "value_2");

        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "您的卡号是多少?");

        Reprompt reprompt = new Reprompt(outputSpeech);

        Response response = new Response(outputSpeech, textCard, reprompt);

        return response;
    }

    /**
     * 处理用户名的具体逻辑
     *
     * @return
     */
    private Response askUserName() {
        TextCard textCard = new TextCard("您的名字叫什么?");
        textCard.setUrl("www:......");
        textCard.setAnchorText("链接文本");
        textCard.addCueWord("您的名字叫什么?");

        // 设置会话信息 TODO
        setSessionAttribute("key_1", "value_1");
        setSessionAttribute("key_2", "value_2");

        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "您的名字是什么?");

        // 构造reprompt
        Reprompt reprompt = new Reprompt(outputSpeech);

        Response response = new Response(outputSpeech, textCard, reprompt);

        return response;
    }



    protected MinShengDplBot(Request request) throws IOException {
        super(request);
    }

    protected MinShengDplBot(String request) throws IOException, JsonMappingException {
        super(request);
    }

    protected MinShengDplBot(Certificate certificate) throws IOException {
        super(certificate);
    }

    protected MinShengDplBot(HttpServletRequest request) throws IOException, JsonMappingException {
        super(request);
    }

    public static void main(String[] args) {
//        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//        System.err.println(path);
}
}
